package com.appliance.cycling2011.download;

import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.ArrayList;

import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.DefaultHttpClient;

import android.content.Context;
import android.widget.Toast;

public class DownloadThread extends Thread {

	// Used for Toast
	protected Toast myToast;
	protected Context context;

	public DownloadThread() {
		// TODO Auto-generated constructor stub
	}
	
	private static ArrayList<String> finished = new ArrayList<String>();

	static public boolean DownloadFromUrl(String url, String directory, final String filename, String extension, int nr) {
		boolean exists = (new File(directory)).exists();
		if (!exists) {
			new File(directory).mkdirs();
		}
		try {
			new DefaultHttpClient().execute(new HttpGet(url)).getEntity()
					.writeTo(new FileOutputStream(new File(directory, filename + '.' + extension)));

			if (!getFinished().contains(Integer.toString(nr))) {
				getFinished().add(Integer.toString(nr));
			}
			return true;

		} catch (ClientProtocolException e) {
			// Log.e("## DOWNLOAD1", e.toString());
			return false;
		} catch (FileNotFoundException e) {
			// Log.e("## DOWNLOAD2", e.toString());
			return false;
		} catch (IOException e) {
			// Log.e("## DOWNLOAD3", e.toString());
			return false;
		}
	}
	

	public void setNewToast(CharSequence s) {
		if (myToast == null) {
			myToast = Toast.makeText(context, s, Toast.LENGTH_SHORT);
		} else {
			myToast.setText(s);
		}
		myToast.show();
	}

	public static ArrayList<String> getFinished() {
		return finished;
	}

	public static void setFinished(ArrayList<String> finished) {
		DownloadThread.finished = finished;
	}
}
